/*
 * AtributoDialog.java
 * 
 * Copyright (C) 2008 David Castellanos Serrano
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package dpoo.gui;

import dpoo.figuras.Parametro;
import dpoo.figuras.Atributo;
import dpoo.figuras.ModVisi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;

/**
 *
 * @author  david
 */
public class AtributoDialog extends javax.swing.JDialog {
    
    private Atributo atributo;
    
    /** Creates new form AtributosDialog */
    public AtributoDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initCheckNombre();
        
        this.setTitle("Nuevo atributo");
        this.atributo = new Atributo("", Parametro.INT, ModVisi.PUBLICO, false, false, false);
    }
    
    
    /** Creates new form AtributosDialog */
    public AtributoDialog(java.awt.Frame parent, boolean modal, Atributo atributo) {
        super(parent, modal);
        initComponents();
        initCheckNombre();
                
        this.setTitle("Modificar atributo");
        this.atributo = atributo;
        this.cargarDatos();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        visiGroup = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        nombre = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        modFinal = new javax.swing.JCheckBox();
        modEstatico = new javax.swing.JCheckBox();
        jLabel3 = new javax.swing.JLabel();
        visiPaquete = new javax.swing.JRadioButton();
        visiPrivada = new javax.swing.JRadioButton();
        visiPublica = new javax.swing.JRadioButton();
        visiProtegido = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        String[] tipos = {"int", "float", "double", "boolean", "String"};
        tipo = new javax.swing.JComboBox(tipos);
        cancelar = new javax.swing.JButton();
        guardar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setLocationByPlatform(true);
        setMinimumSize(new java.awt.Dimension(457, 216));

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel1.setText("Nombre:");

        jLabel4.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel4.setText("Modificadores:");

        modFinal.setText("Final");

        modEstatico.setText("Estático");

        jLabel3.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel3.setText("Visibilidad:");

        visiGroup.add(visiPaquete);
        visiPaquete.setSelected(true);
        visiPaquete.setText("Paquete");

        visiGroup.add(visiPrivada);
        visiPrivada.setText("Privada");

        visiGroup.add(visiPublica);
        visiPublica.setText("Pública");

        visiGroup.add(visiProtegido);
        visiProtegido.setText("Protegido");

        jLabel2.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel2.setText("Tipo:");

        cancelar.setText("Cancelar");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        guardar.setText("Guardar");
        guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nombre, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tipo, 0, 390, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(visiPaquete)
                            .addComponent(visiPrivada))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(visiPublica)
                            .addComponent(visiProtegido)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(modEstatico)
                            .addComponent(modFinal)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(guardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(visiPaquete)
                    .addComponent(visiProtegido))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(visiPrivada)
                    .addComponent(visiPublica))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(modFinal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(modEstatico)
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelar)
                    .addComponent(guardar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Inicializa el chequeo del nombre del Atributo en el AtributoDialog
     */
    private void initCheckNombre() {
        //estoy al tanto de los cambios que ocurrieran en el nombre del atributo
        Document doc = this.nombre.getDocument();
        doc.addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent arg0) {
                nombreTextChange();
            }

            public void removeUpdate(DocumentEvent arg0) {}

            public void changedUpdate(DocumentEvent arg0) {
                nombreTextChange();
            }
        });
        
        //la venganza se sirve fría: impido que el usuario cierre la ventana sin usar los botones guardar o cancelar
        this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    }
    
private void guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarActionPerformed
    //¿es el nombre del atributo correcto?
    if(this.comprobarNombre()) {
        //actualizo el Atributo
        this.atributo.setNombre(this.nombre.getText());
        this.atributo.setTipo(this.tipo.getSelectedIndex());

        //rollo de visibilidad, modificadores, etc.
        ModVisi modVisi = this.atributo.getModVisi();
        modVisi.setModEstatico(this.modEstatico.isSelected());
        modVisi.setModFinal(this.modFinal.isSelected());
        if(this.visiPaquete.isSelected()) {
            modVisi.setVisibilidad(ModVisi.PAQUETE);
        }
        if(this.visiPrivada.isSelected()) {
            modVisi.setVisibilidad(ModVisi.PRIVADO);
        }
        if(this.visiProtegido.isSelected()) {
            modVisi.setVisibilidad(ModVisi.PROTEGIDO);
        }
        if(this.visiPublica.isSelected()) {
            modVisi.setVisibilidad(ModVisi.PUBLICO);
        }

        //oculto el diálogo
        this.setVisible(false);
    } else {
        //si es incorrecto le lanzo el maravilloso cuadro de error
        this.nombreTextChange();
    }
}//GEN-LAST:event_guardarActionPerformed

private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
    this.atributo = null;
    this.setVisible(false);
}//GEN-LAST:event_cancelarActionPerformed


    /**
     * Carga los datos del Atributo en el AtributoDialog
     */
    private void cargarDatos() {
        this.nombre.setText(this.atributo.getNombre());
        this.tipo.setSelectedIndex(this.atributo.getTipo());
        
        ModVisi modVisi = this.atributo.getModVisi();
        
        switch(modVisi.getVisibilidad()) {
            case ModVisi.PAQUETE:
                this.visiPaquete.setSelected(true);
                break;
            case ModVisi.PRIVADO:
                this.visiPrivada.setSelected(true);
                break;
            case ModVisi.PROTEGIDO:
                this.visiProtegido.setSelected(true);
                break;
            case ModVisi.PUBLICO:
                this.visiPublica.setSelected(true);
                break;
        }
        this.modEstatico.setSelected(modVisi.getModEstatico());
        this.modFinal.setSelected(modVisi.getModFinal());
    }
    
    /**
     * Devuelve el Atributo creado por el AtributoDialog
     * @return
     */
    public Atributo getAtributo() {
        return this.atributo;
    }
    
    
    //COMPROBAR QUE EL CONTENIDO DEL AtributoDialog ES CORRECTO
    /**
     * Comprueba que el nombre del Atributo sea correcto
     * @return
     */
    private boolean comprobarNombre() {
        //Debe comenzar con una letra minúscula, y después tener letras, números o _
        Pattern pc = Pattern.compile("\\p{Lower}+\\w*");
        Matcher m = pc.matcher(this.nombre.getText());
        
        return m.matches();
    }

    /**
     * Si el nombre del atributo es incorrecto muestra un cuadro de diálogo informando al usuario
     */
    private void nombreTextChange() {
        if(!this.comprobarNombre()) {
            String msgText = "<html>Para que el nombre de un atributo sea válido, debe cumplir las siguientes condiciones:<ul>" +
                "<li>Debe comenzar con una letra minúscula (a-z).</li>" +
                "<li>Constar únicamente de letras (a-z, A-Z), números (0-9) o el caracter _.</li><ul></html>";
            JOptionPane.showMessageDialog(this, msgText, "Nombre de atributo incorrecto", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelar;
    private javax.swing.JButton guardar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JCheckBox modEstatico;
    private javax.swing.JCheckBox modFinal;
    private javax.swing.JTextField nombre;
    private javax.swing.JComboBox tipo;
    private javax.swing.ButtonGroup visiGroup;
    private javax.swing.JRadioButton visiPaquete;
    private javax.swing.JRadioButton visiPrivada;
    private javax.swing.JRadioButton visiProtegido;
    private javax.swing.JRadioButton visiPublica;
    // End of variables declaration//GEN-END:variables
    
}
